package com.small.auth.granter;

import com.small.auth.service.CustomUserDetailsService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

/**
 * 小程序登录
 *
 * @author wangguochao
 */
public class WxWeChatCustomTokenGranter extends AbstractTokenGranter {

    protected CustomUserDetailsService userDetailsService;

    public WxWeChatCustomTokenGranter(CustomUserDetailsService userDetailsService,
                                      AuthorizationServerTokenServices tokenServices,
                                      ClientDetailsService clientDetailsService,
                                      OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, "wx-xcx-login");
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = tokenRequest.getRequestParameters();
        UserDetails details = userDetailsService.loadUserByJsCode(parameters);
        Authentication userAuth = new UsernamePasswordAuthenticationToken(details.getUsername(),
                details.getPassword(), details.getAuthorities());
        OAuth2Request storedOAuthRequest = getRequestFactory().createOAuth2Request(client, tokenRequest);
        OAuth2Authentication authentication = new OAuth2Authentication(storedOAuthRequest, userAuth);
        authentication.setDetails(details);
        authentication.setAuthenticated(true);
        return authentication;
    }

}
